<?php

/**
 * Processor for movie images
 */
class ImageProcessor {

    /**
     * Convert PNG to JPEG
     * 
     * @param string $originalFile  Contains path of original file
     * @param string $outputFile    Contains path of result file
     */
    private function _pngToJpg($originalFile, $outputFile) {
        $image = imagecreatefrompng($originalFile);
        imagejpeg($image, $outputFile, 100);
        imagedestroy($image);
    }

    /**
     * Resample image
     * 
     * @param string $originalFile  Contains path to original file
     * @param type $outputFile      Contains path to output file
     * @param type $newWidth        Contains new width
     */
    private function _imageResample($originalFile, $outputFile, $newWidth) {
        list($width, $height) = getimagesize($originalFile);
        $ratio = $width / $height;
        $newHeight = $newWidth / $ratio;
        // Resample
        $imageProcessed = imagecreatetruecolor($newWidth, $newHeight);
        $image = imagecreatefromjpeg($originalFile);
        imagecopyresampled($imageProcessed, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        // Save result
        imagejpeg($imageProcessed, $outputFile, 100);
        imagedestroy($image);
        imagedestroy($imageProcessed);
    }

    /**
     * Save image from URL
     * 
     * @param string $imageUrl  Conains URL
     * @param string $filename  Contains relative result path
     * 
     * @return bool
     */
    public function saveImage($imageUrl, $filename) {
        $imagePath = Yii::app()->basePath . '/../images/' . $filename;
        file_put_contents($imagePath, file_get_contents($imageUrl));
        // Check PNG
        if (preg_match('/\.png$/i', $imageUrl)) {
            $this->_pngToJpg($imagePath, $imagePath);
        }
        $result = (file_exists($imagePath) && filesize($imagePath) > 0) ? true : false;
        return $result;
    }

    /**
     * Create small image
     * 
     * @param string $originalFile  Contains relative path to original file
     * @param string $outputFile    Contains relative path to output file
     * 
     * @return bool
     */
    public function crateSmallImage($originalFile, $outputFile) {
        $sourcePath = Yii::app()->basePath . '/../images/' . $originalFile;
        $destinationPath = Yii::app()->basePath . '/../images/' . $outputFile;
        $this->_imageResample($sourcePath, $destinationPath, 150);
        $result = (file_exists($destinationPath) && filesize($destinationPath) > 0) ? true : false;
        return $result;
    }
    
    /**
     * Remove image
     * 
     * @param string $filename  Contains relative path to file
     */
    public function removeImage($filename) {
        $imagePath = Yii::app()->basePath . '/../images/' . $filename;
        unlink($imagePath);
    }
    
    

}
